package com.fhc.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Error
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

class FhcMailSend {
}

val EMAIL_HOST_REGEX = "^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$".toRegex()
// 匹配如 smtp.163.com 或 mail.example.com 的格式


val PORT_REGEX = "^([1-9]\\d{0,3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])$".toRegex()
// 匹配1-65535的有效端口范围


val EMAIL_REGEX = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$".toRegex()
// 标准邮箱格式验证  允许字母、数字、点号、下划线、百分号、加号和减号，主域名（murata）包含字母和减号
//顶级域名（com）为2-6个字母37
//符合"必须存在一个@和一个."的要求8


val PASSWORD_REGEX = "^[\\x20-\\x7E]{8,32}$".toRegex()
// 匹配8-32位可打印ASCII字符（包括空格）

val NOT_BLANK_REGEX = "^\\s*(\\S+\\s*)+$".toRegex()
// 匹配至少包含1个非空白字符的字符串:ml-citation{ref="7,10" data="citationList"}

val BODY_REGEX = "^[\\s\\S]{1,10000}$".toRegex()
// 允许1-10000个任意字符（包括换行）

@Preview(showBackground = true)
@Composable
fun EmailScreen() {
        var hostVal by remember {mutableStateOf("1")}
        var bodyVal by remember {mutableStateOf("\r\n\r\n\r\n\r\n")}
        Column(modifier = Modifier .fillMaxSize().padding(16.dp)) {
            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(EMAIL_HOST_REGEX)
                val errorMessage = "请输入6-12位字母或数字"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(EMAIL_HOST_REGEX)
                    },
                    label = {
                        Text("SMTP服务器", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )

            }
            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(PORT_REGEX)
                val errorMessage = "请输入6-12位字母或数字"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(PORT_REGEX)
                    },
                    label = {
                        Text("端口号", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }

            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(EMAIL_REGEX)
                val errorMessage = "请输入6-12位字母或数字"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(EMAIL_REGEX)
                    },
                    label = {
                        Text("发件邮箱", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }

            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(PASSWORD_REGEX)
                val errorMessage = "8-32位ASCII字符 (非登录密码)"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(PASSWORD_REGEX)
                    },
                    label = {
                        Text("SMTP授权码", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }


            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(EMAIL_REGEX)
                val errorMessage = "请输入6-12位字母或数字"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(EMAIL_REGEX)
                    },
                    label = {
                        Text("收件邮箱", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }


            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !hostVal.matches(NOT_BLANK_REGEX)
                val errorMessage = "请输入6-12位字母或数字"
                OutlinedTextField(
                    value = hostVal,
                    onValueChange = {
                        hostVal = it.take(10)
                        isError = !hostVal.matches(NOT_BLANK_REGEX)
                    },
                    label = {
                        Text("邮件主题", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }
            Row(modifier = Modifier.padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                val borderColor = colorResource(id = android.R.color.darker_gray)
                val errorColor = colorScheme.error
                var isError by remember { mutableStateOf(false) }
                isError = !bodyVal.matches(NOT_BLANK_REGEX)
                val errorMessage = "内容不可为空"
                OutlinedTextField(
                    value = bodyVal,
                    onValueChange = {
                        bodyVal = it.take(1000)
                        isError = !bodyVal.matches(NOT_BLANK_REGEX)
                    },
                    label = {
                        Text("邮件正文", color = if (isError) errorColor else borderColor,)
                    },
                    isError = isError,
                    supportingText = {
                        if (isError) {
                            Text(text = errorMessage, color = colorScheme.error)
                        }
                    },
                    trailingIcon = {
                        if (isError) {
                            Icon(
                                Icons.Filled.Error,
                                "error",
                                tint = colorScheme.error
                            )
                        }
                    },
                    singleLine = false,
                    modifier = Modifier.fillMaxWidth(),
                    shape = MaterialTheme.shapes.medium,
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = Color.Transparent,
                        focusedContainerColor = Color.Transparent,
                        errorContainerColor = Color.Transparent,
                        focusedBorderColor = if (isError) errorColor else borderColor,
                        unfocusedBorderColor = if (isError) errorColor else borderColor,
                        errorBorderColor = errorColor,
                        disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
                        cursorColor = if (isError) errorColor else MaterialTheme.colorScheme.primary
                    )
                )
            }
        }

}


object EmailSender {
    fun send(
        host: String,          // SMTP服务器（如 smtp.163.com）
        port: String,          // 端口号（如 465）
        username: String,      // 发件邮箱（完整地址）
        password: String,      // SMTP授权码⚠️非登录密码
        to: String,            // 收件邮箱
        subject: String,       // 邮件主题
        body: String           // 邮件正文
    ) = CoroutineScope(Dispatchers.IO).launch {
        val props = Properties().apply {
            put("mail.smtp.auth", "true")
            put("mail.smtp.starttls.enable", "true")
            put("mail.smtp.host", host)
            put("mail.smtp.port", port)
            put("mail.smtp.ssl.enable", "true") // 启用SSL加密
        }

        try {
            val session = Session.getInstance(props,
                object : Authenticator() {
                    override fun getPasswordAuthentication() =
                        PasswordAuthentication(username, password)
                }
            )

            MimeMessage(session).apply {
                setFrom(InternetAddress(username))
                addRecipient(Message.RecipientType.TO, InternetAddress(to))
                setSubject(subject)
                setText(body)
                Transport.send(this)
            }
        } catch (e: MessagingException) {
            e.printStackTrace()
        }
    }
}